package siau.android.base

import com.umeng.analytics.MobclickAgent
import hhm.android.http.RequestErrorThrowable
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableSource
import io.reactivex.rxjava3.functions.Function
import siau.android.library.KeyString


class ThrowableFunc<T> : Function<Throwable, ObservableSource<T>> {
    override fun apply(t: Throwable): ObservableSource<T> {
        return if (t is RequestErrorThrowable) {
            if (t.errorCode == "-1") {
                KeyString.token = ""
                SBApplication.sendOnePointReceiver(false)
                Observable.error(RequestErrorThrowable("-1", "账号已在别处登录，请重新登录"))
            } else {
                if (HttpHelper.isOnLine()) {
                    MobclickAgent.reportError(SBApplication.instance.applicationContext, t)
                }
                Observable.error(t)
            }
        } else {
            if (HttpHelper.isOnLine()) {
                MobclickAgent.reportError(SBApplication.instance.applicationContext, t)
            }
            if (t.message?.startsWith("Failed to connect to") == true) {
                Observable.error(Throwable("网络异常，请检查网络或稍后重试"))
            } else {
                Observable.error(Throwable("服务器开小差了，请稍后再试"))
            }
        }
    }
}